package com.jvm123.api.api.controller;

import com.jvm123.api.api.client.PostsClient;
import com.jvm123.api.api.entity.Post;
import com.jvm123.api.api.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 同步blog
 * @author yawn http://jvm123.com
 * 2019/12/5 9:51
 */
@RestController
@RequestMapping("sync")
public class SyncController {


    @Autowired
    private PostsClient postsClient;
    @Autowired
    private PostService postService;

    /**
     * 全量同步
     */
    @GetMapping("all")
    public boolean syncAll() {
        int page = 0, size = 10;
        List<Post> postList;
        do {
            postList = postsClient.page(page, size);
            postList.forEach(this::parse);
            postService.add(postList);
            page++;
        } while (postList.size() >= size);

        return true;
    }

    /**
     * 手动同步
     */
//    @GetMapping("rest")
//    public boolean syncRest() {
//        syncBlog();
//        return true;
//    }

    /**
     * 将博客定时同步到elasticsearch中（增量同步）
     */
//    @Scheduled(cron = "0 0 3 * * *")
////    @Scheduled(initialDelay = 10000, fixedDelay = 1000000)
//    public void syncBlog() {
//        long maxPostId = postService.maxPostId();
//        List<Post> postList = postsClient.page(maxPostId);
//        if (postList.isEmpty()) {
//            return;
//        }
//        postList.forEach(this::parse);
//        postService.saveAll(postList);
//    }





    private void parse(Post post) {
        String content = post.getPostContent();
        StringBuffer sb = new StringBuffer();

        for (int start, end = -1; (start = content.indexOf('<', end)) != -1; ) {
            sb.append(content, end + 1, start).append(" ");
            end = content.indexOf('>', start);
        }
        post.setPostContent(new String(sb));
    }
}